//
//  PlayController.m
//  Kugou-OC
//
//  Created by BH on 16/5/18.
//  Copyright © 2016年 Sunny. All rights reserved.
//

#import "PlayController.h"
#import "GlobalDefine.h"
#import "MusicInfoModel.h"
#import "BottomPlayView.h"
#import "NSTimer+Control.h"
#import "PlayHelper.h"
#import "HomeController.h"
#import <MediaPlayer/MediaPlayer.h>
#import <MBProgressHUD/MBProgressHUD.h>
#import <SDWebImage/UIImageView+WebCache.h>
#import <SDAutoLayout/UIView+SDAutoLayout.h>

@interface PlayController (){
    PlayMode playMode;//播放模式
}
//背景图
@property (weak, nonatomic) IBOutlet UIImageView *bgImg;
//歌曲名
@property (weak, nonatomic) IBOutlet UILabel *singNameLab;
//歌手
@property (weak, nonatomic) IBOutlet UILabel *singerLab;
//下载
@property (weak, nonatomic) IBOutlet UIButton *downloadBtn;
//收藏
@property (weak, nonatomic) IBOutlet UIButton *favoriteBtn;
//专辑封面
@property (weak, nonatomic) IBOutlet UIImageView *albumImg;
//当前播放时间
@property (weak, nonatomic) IBOutlet UILabel *currentTimeLab;
//总时长
@property (weak, nonatomic) IBOutlet UILabel *totalTimeLab;
//时间滑块
@property (weak, nonatomic) IBOutlet UISlider *timeSlider;
//播放模式
@property (weak, nonatomic) IBOutlet UIButton *playModeBtn;
//播放
@property (weak, nonatomic) IBOutlet UIButton *playBtn;
//模糊层
@property (nonatomic, strong) UIVisualEffectView *blurEffectView;
//音量
@property (weak, nonatomic) IBOutlet UISlider *volumnSlider;

@end

@implementation PlayController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];

    //播放进度滑块
    [_timeSlider setThumbImage:IMAGE(@"playview_slider_thumbimage") forState:UIControlStateNormal];
    [_timeSlider setThumbImage:IMAGE(@"playview_slider_thumbimage") forState:UIControlStateHighlighted];
    //音量滑块
    [_volumnSlider setThumbImage:IMAGE(@"playview_slider_thumbimage") forState:UIControlStateNormal];
    [_volumnSlider setThumbImage:IMAGE(@"playview_slider_thumbimage") forState:UIControlStateHighlighted];
    _volumnSlider.transform = CGAffineTransformMakeRotation(-M_PI/2);
    _volumnSlider.hidden = YES;
    
    //判断bottom传来的Item是否是正在播放的
    if (_playerItem) {
        _currentTimeLab.text = [self timeformatFromSeconds:CMTimeGetSeconds(_playerItem.currentTime) - 1];
        _totalTimeLab.text = [self timeformatFromSeconds:CMTimeGetSeconds(_playerItem.duration)];
        _timeSlider.maximumValue = CMTimeGetSeconds(_playerItem.duration);
        _timeSlider.value = CMTimeGetSeconds(_playerItem.currentTime);
    }
    //播放模式
    playMode = (PlayMode)[USERDEFAULT valueForKey:@"playMode"];
    if (playMode == kPlayModeRandom) {
        [_playModeBtn setImage:IMAGE(@"playview_random") forState:UIControlStateNormal];
    }else if (playMode == kPlayModeCycle){
        [_playModeBtn setImage:IMAGE(@"playview_cycle") forState:UIControlStateNormal];
    }
    //设置播放数据
    [self setUpPlayDataWithMusicModel:_singsList[_currentIndex]];
}

//时间格式化
- (NSString *)timeformatFromSeconds:(NSInteger)seconds {
    NSInteger totalm = seconds/(60);
    NSInteger h = totalm/(60);
    NSInteger m = totalm%(60);
    NSInteger s = seconds%(60);
    if (h == 0) {
        return  [NSString stringWithFormat:@"%02ld:%02ld", (long)m, (long)
                 s];
    }
    return [NSString stringWithFormat:@"%02ld:%02ld:%02ld", (long)h, (long)m, (long)s];
}

/**
 *  popController
 */
- (IBAction)backAction:(id)sender {
    [self setUpBottomView];
    
    [self.view removeFromSuperview];

}

/**
 *  下载
 */
- (IBAction)downloadAction:(id)sender {
}

/**
 *  分享
 */
- (IBAction)shareAction:(id)sender {
}

/**
 *  收藏
 */
- (IBAction)favoriteAction:(id)sender {
}

/**
 *  音量
 */
- (IBAction)setVolumn:(id)sender {
//    if (_volumnSlider.hidden) {
//        _volumnSlider.hidden = NO;
//    }else{
//        _volumnSlider.hidden = YES;
//    }
//    MPMusicPlayerController *mp=[MPMusicPlayerController applicationMusicPlayer];
//    mp.volume = _volumnSlider.value;
}

/**
 *  播放模式
 */
- (IBAction)playModeAction:(id)sender {
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeText;
    
    if (playMode != kPlayModeRandom) {
        [_playModeBtn setImage:IMAGE(@"playview_random") forState:UIControlStateNormal];
        hud.labelText = @"随机模式";
        playMode = kPlayModeRandom;
    }else if (playMode != kPlayModeCycle){
        [_playModeBtn setImage:IMAGE(@"playview_cycle") forState:UIControlStateNormal];
        hud.labelText = @"单曲循环";
        playMode = kPlayModeCycle;
    }else{
        [_playModeBtn setImage:IMAGE(@"playview_serious") forState:UIControlStateNormal];
        hud.labelText = @"顺序播放";
        playMode = kPlayModeSerious;
    }
    [USERDEFAULT setValue:@(playMode) forKey:@"playMode"];
    [hud hide:YES afterDelay:0.5];
}

/**
 *  上一首
 */
- (IBAction)previousAction:(id)sender {
    
    if (_playerItem == nil) {
        return;
    }
    
    //当前列表只有一首歌
    if (_singsList.count == 1) {
        MBProgressHUD *mb = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        mb.mode = MBProgressHUDModeText;
        mb.labelText = @"-.-只有一首歌";
        [mb hide:YES afterDelay:0.5];
        return;
    }
    
    //切换上一首
    [BottomPlayView shareBottomView].playerItem = nil;
    [_playBtn setImage:IMAGE(@"bottom_play") forState:UIControlStateNormal];
    if (playMode == kPlayModeRandom) {
        [self randomPlaySong];
    }else if(playMode == kPlayModeSerious){
        if (--_currentIndex >= 0) {
            
            [self setUpPlayDataWithMusicModel:_singsList[_currentIndex]];
        }else{
            _currentIndex = _singsList.count-1;
            [self setUpPlayDataWithMusicModel:[_singsList lastObject]];
        }
    }else{
        [self cyclePlaySong];
    }
    
    //设置底部bottomview
    [self setUpBottomView];
}

/**
 *  播放
 */
- (IBAction)playAction:(id)sender {
    
    if (_playerItem == nil) {
        return;
    }
    
    PlayHelper *playHepler = [PlayHelper sharePlayHelper];
    BOOL isPlaying = [USERDEFAULT boolForKey:@"isPlaying"];
    if (!isPlaying) {
        [_playBtn setImage:IMAGE(@"playview_play") forState:UIControlStateNormal];
        [playHepler.aPlayer play];
        [[BottomPlayView shareBottomView].playerTimer resumeTimer];
    }else{
        [_playBtn setImage:IMAGE(@"playview_pause") forState:UIControlStateNormal];
        [playHepler.aPlayer pause];
        [[BottomPlayView shareBottomView].playerTimer pauseTimer];
    }
    
    [USERDEFAULT setBool:!isPlaying forKey:@"isPlaying"];
}

/**
 *  下一首
 */
- (IBAction)nextAction:(id)sender {
    
    if (!_playerItem) {
        return;
    }
    
    //当前列表只有一首歌
    if (_singsList.count == 1) {
        MBProgressHUD *mb = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        mb.mode = MBProgressHUDModeText;
        mb.labelText = @"-.-只有一首歌";
        [mb hide:YES afterDelay:0.5];
        return;
    }
    //播放下一首
    if (playMode == kPlayModeRandom) {
        [self randomPlaySong];
    }else if(playMode == kPlayModeSerious){
        [self nextSong];
    }else{
        [self cyclePlaySong];
    }
}

/**
 *  播放列表
 */
- (IBAction)playListAction:(id)sender {
}

/**
 *  拖动滑块
 */
- (IBAction)sliderValueChanged:(id)sender {
    UISlider *slider = (UISlider*)sender;

    //当前播放不存在
    if (!_playerItem) {
        return;
    }
    
    self.currentTimeLab.text = [self timeformatFromSeconds:slider.value];
    [[BottomPlayView shareBottomView].playerTimer pauseTimer];
}

/**
 *  拖动结束
 */
- (IBAction)sliderDragDone:(id)sender {
    UISlider *slider = (UISlider*)sender;
    if (!_playerItem) {
        _timeSlider.value = 0;
        return;
    }
    
    [[BottomPlayView shareBottomView].playerTimer resumeTimer];
    _timeSlider.value = slider.value;
    CMTime dragedTime = CMTimeMake(slider.value, 1);
    [[PlayHelper sharePlayHelper].aPlayer pause];
    [[PlayHelper sharePlayHelper].aPlayer seekToTime:dragedTime completionHandler:^(BOOL finished) {
        [[PlayHelper sharePlayHelper].aPlayer play];
    }];
}

#pragma mark 设置数据
- (void)setUpPlayDataWithMusicModel:(MusicInfoModel *)model {
    
    //创建模糊层
    UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
    [_blurEffectView removeFromSuperview];//移除上次模糊层
    self.blurEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
    _blurEffectView.frame = self.view.bounds;
    [self.bgImg insertSubview:_blurEffectView atIndex:0];
    [self.bgImg sd_setImageWithURL:[NSURL URLWithString:model.music_icon] placeholderImage:IMAGE(@"playview_placeholder_pic")];
    self.albumImg.layer.cornerRadius = self.albumImg.width/2;
    self.albumImg.layer.masksToBounds = YES;
    self.albumImg.image = self.bgImg.image;
    
    if (model == nil) {
        //没有歌曲播放
        self.singNameLab.text = [NSString stringWithFormat:@"没有选择播放的歌曲"];
        self.singerLab.text = @"微乐提醒";
        self.currentTimeLab.text = @"00:00";
        self.totalTimeLab.text = @"00:00";
        self.timeSlider.value = 0;
        return;
    }
    
    self.singNameLab.text = model.music_name;
    self.singerLab.text = model.music_artist;
    
    BottomPlayView *bpv = [BottomPlayView shareBottomView];
    
    if (bpv.playerItem.status == AVPlayerStatusReadyToPlay) {
        bpv.ASTimer = ^(AVPlayerItem *item){
            [self handleActionTime:item];
        };
    }else{
        [[BottomPlayView shareBottomView] setupPlayerWithModel:model];
        bpv.ASTimer = ^(AVPlayerItem *item){
            [self handleActionTime:item];
        };
    }
    
    //播放下一首
    bpv.NextSong = ^() {
        //给系统一个延迟，准备播放下一首(如果不延迟，将不能自己播放下一首ps:或许player还没有准备好播放)
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if (playMode == kPlayModeRandom) {
                [self randomPlaySong];
            }else if(playMode == kPlayModeSerious){
                [self nextSong];
            }else{
                [self cyclePlaySong];
            }
        });
    };
}

//计时器
-(void)handleActionTime:(AVPlayerItem *)item{
    [_playBtn setImage:IMAGE(@"playview_play") forState:UIControlStateNormal];
    self.currentTimeLab.text = [self timeformatFromSeconds:CMTimeGetSeconds(item.currentTime)];
    self.totalTimeLab.text = [self timeformatFromSeconds:CMTimeGetSeconds(item.duration)];
    self.timeSlider.maximumValue = CMTimeGetSeconds(item.duration);
    self.timeSlider.value = CMTimeGetSeconds(item.currentTime);
    
    //这里需要存储一下当前的playerItem,以便pop时，还给bottomView
    _playerItem = item;
    
    [UIView animateWithDuration:2 animations:^{
        self.albumImg.transform = CGAffineTransformRotate(self.albumImg.transform, M_PI / 90);
    }];
}

//循环播放
-(void)cyclePlaySong{
    [BottomPlayView shareBottomView].playerItem = nil;
    [self setUpPlayDataWithMusicModel:_singsList[_currentIndex]];
    [self setUpBottomView];
}

//随机播放一首歌
- (void)randomPlaySong {
    //将当期页设置为随机的数
    NSInteger index = arc4random() % _singsList.count;
    _currentIndex = index;
    [BottomPlayView shareBottomView].playerItem = nil;
    [self setUpPlayDataWithMusicModel:_singsList[index]];
    [self setUpBottomView];
}

//获取下一首歌曲
-(void)nextSong{
    [BottomPlayView shareBottomView].playerItem = nil;
    
    [_playBtn setImage:IMAGE(@"bottom_play") forState:UIControlStateNormal];
    if (++_currentIndex >= _singsList.count) {
        _currentIndex = 0;
        [self setUpPlayDataWithMusicModel:[_singsList firstObject]];
    }else{
        [self setUpPlayDataWithMusicModel:_singsList[_currentIndex]];
    }
    
    [self setUpBottomView];
}

//重新给bottomplayview赋值
-(void)setUpBottomView{
    BottomPlayView *bpv = [BottomPlayView shareBottomView];
    bpv.musicList = _singsList;
    bpv.currentPlayIndex = _currentIndex;
    bpv.currentPlayer = _playerItem;
    
    MusicInfoModel *model = _singsList[_currentIndex];
    [bpv.iconImg sd_setImageWithURL:[NSURL URLWithString:model.music_icon] placeholderImage:IMAGE(@"bottom_placeholder_image")];
    bpv.singNameLab.text = model.music_name==nil?@"未知":model.music_name;
    bpv.singerLab.text = model.music_artist==nil?@"未知":model.music_artist;
    bpv.silder.value = _timeSlider.value;
    if ([USERDEFAULT boolForKey:@"isPlaying"]) {
        [bpv.playBtn setImage:IMAGE(@"bottom_play") forState:UIControlStateNormal];
    }else{
        [bpv.playBtn setImage:IMAGE(@"bottom_pause") forState:UIControlStateNormal];
    }
}
@end
